<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="关联主表ID" prop="mainId">
        <el-input
          v-model="queryParams.mainId"
          placeholder="请输入关联主表ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="二维码唯一标识" prop="qrCodeId">
        <el-input
          v-model="queryParams.qrCodeId"
          placeholder="请输入二维码唯一标识"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入产品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品编码" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入产品编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="规格" prop="specification">
        <el-input
          v-model="queryParams.specification"
          placeholder="请输入规格"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="单位" prop="unit">
        <el-input
          v-model="queryParams.unit"
          placeholder="请输入单位"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="厂家地址" prop="manufacturer">
        <el-input
          v-model="queryParams.manufacturer"
          placeholder="请输入厂家地址"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="批次号" prop="batchNumber">
        <el-input
          v-model="queryParams.batchNumber"
          placeholder="请输入批次号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['md:sub:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['md:sub:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['md:sub:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['md:sub:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="subList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" align="center" prop="id" />
      <el-table-column label="关联主表ID" align="center" prop="mainId" />
      <el-table-column label="二维码唯一标识" align="center" prop="qrCodeId" />
      <el-table-column label="产品名称" align="center" prop="productName" />
      <el-table-column label="产品编码" align="center" prop="code" />
      <el-table-column label="产品图片" align="center">
        <template slot-scope="scope">
          <el-image
              v-if="scope.row.productImageUrl"
              :src="scope.row.productImageUrl"
              :preview-src-list="[scope.row.productImageUrl]"
              style="width: 80px; height: 80px"
              fit="cover"
          >
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline"></i>
            </div>
          </el-image>
          <span v-else>—</span>
        </template>
      </el-table-column>
      <el-table-column label="二维码" align="center">
        <template slot-scope="scope">
          <el-image
            v-if="scope.row.qrCodeImage"
            :src="getFullQrCodePath(scope.row.qrCodeImage)"
            :preview-src-list="[getFullQrCodePath(scope.row.qrCodeImage)]"
            style="width: 40px; height: 40px"
            fit="cover"
          >
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline"></i>
            </div>
          </el-image>
        </template>
      </el-table-column>

      <el-table-column label="产品属性" align="center" prop="attributes" />
      <el-table-column label="规格" align="center" prop="specification" />
      <el-table-column label="单位" align="center" prop="unit" />
      <el-table-column label="厂家地址" align="center" prop="manufacturer" />
      <el-table-column label="批次号" align="center" prop="batchNumber" />
      <el-table-column label="说明" align="center" prop="description" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['md:sub:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['md:sub:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改溯源码子对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="关联主表ID" prop="mainId">
          <el-input v-model="form.mainId" placeholder="请输入关联主表ID" />
        </el-form-item>
        <el-form-item label="二维码唯一标识" prop="qrCodeId">
          <el-input v-model="form.qrCodeId" placeholder="请输入二维码唯一标识" />
        </el-form-item>
        <el-form-item label="产品名称" prop="productName">
          <el-input v-model="form.productName" placeholder="请输入产品名称" />
        </el-form-item>
        <el-form-item label="产品编码" prop="code">
          <el-input v-model="form.code" placeholder="请输入产品编码" />
        </el-form-item>
        <el-form-item label="产品图片">
          <div v-if="form.productImageUrl">
            <img :src="form.productImageUrl" alt="产品图片" style="max-width: 200px; max-height: 200px;" />
          </div>
          <div v-else>暂无图片</div>
        </el-form-item>
        <el-form-item label="凭证图片" prop="imageUrl">
          <el-input v-model="form.imageUrl" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="产品属性" prop="attributes">
          <el-input v-model="form.attributes" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="规格" prop="specification">
          <el-input v-model="form.specification" placeholder="请输入规格" />
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input v-model="form.unit" placeholder="请输入单位" />
        </el-form-item>
        <el-form-item label="厂家地址" prop="manufacturer">
          <el-input v-model="form.manufacturer" placeholder="请输入厂家地址" />
        </el-form-item>
        <el-form-item label="批次号" prop="batchNumber">
          <el-input v-model="form.batchNumber" placeholder="请输入批次号" />
        </el-form-item>
        <el-form-item label="说明" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listSub, getSub, delSub, addSub, updateSub } from "@/api/mes/qr/sub";

export default {
  name: "Sub",
  data() {
    return {
      // 遮罩层
      loading: true,
      apiBaseURL: process.env.VUE_APP_BASE_API || '',
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 溯源码子表格数据
      subList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        mainId: null,        qrCodeId: null,        productName: null,        code: null,        imageUrl: null,        attributes: null,        specification: null,        unit: null,        manufacturer: null,        batchNumber: null,        description: null      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        mainId: [
          { required: true, message: "关联主表ID不能为空", trigger: "blur" }
        ],        qrCodeId: [
          { required: true, message: "二维码唯一标识不能为空", trigger: "blur" }
        ],        productName: [
          { required: true, message: "产品名称不能为空", trigger: "blur" }
        ],        code: [
          { required: true, message: "产品编码不能为空", trigger: "blur" }
        ],      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询溯源码子列表 */
    getList() {
      this.loading = true;
      listSub(this.queryParams).then(response => {
        console.log('接口返回:', response);
        console.log('拼接后的图片路径:', response.rows[0]?.qrCodeImage);
        this.subList = response.rows || [];
        this.total = response.total;
        this.loading = false;
      }).catch(err => {
        console.error('接口请求失败:', err);
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,        mainId: null,        qrCodeId: null,        productName: null,        code: null,        imageUrl: null,        attributes: null,        specification: null,        unit: null,        manufacturer: null,        batchNumber: null,        description: null      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加溯源码子";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getSub(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改溯源码子";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateSub(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSub(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除溯源码子编号为"' + ids + '"的数据项？').then(function() {
        return delSub(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('md/sub/export', {
        ...this.queryParams
      }, `sub_${new Date().getTime()}.xlsx`)
    },
    getFullQrCodePath(relativePath) {
      try {
        if (!relativePath) return '';

        if (relativePath.startsWith('http')) {
          return relativePath;
        }

        // 处理相对路径
        const basePath = process.env.VUE_APP_BASE_API || '';
        const normalizedBasePath = basePath.endsWith('/') ? basePath : basePath + '/';

        // 如果路径已经包含在base API中，避免重复拼接
        if (relativePath.startsWith('/qrcode/')) {
          return normalizedBasePath + relativePath.substring(1);
        }

        return normalizedBasePath + relativePath;
      } catch (error) {
        console.error('错误处理QR码路径:', error);
        return '';
      }
    }
  }
};
</script>
